#include "ET++.ph"
#ifdef __GNUG__
#pragma implementation
#endif

#include "ShellTool.h"

#include "Class.h"
#include "Window.h"
#include "Scroller.h"
#include "ShellTView.h"
#include "CommandProcessor.h"
#include "StyledText.h"
#include "MenuBar.h"
#include "Menu.h"
#include "Env.h"
#include "String.h"

const int cSHOWERR = cUSERCMD + 2;

//---- ShellTool ---------------------------------------------------------------

NewMetaImpl(ShellTool, Manager, (TP(view), TP(text), T(cnt)));

int ShellTool::shellcnt;

ShellTool::ShellTool() : Manager()
{
	cnt= ShellTool::shellcnt++;
	fd= gFixedFont;
	if (Env::GetValue("ShellText.UseStyles", TRUE))
		text= new StyledText(256, fd);
	else
		text= new GapText(256, fd);
}

ShellTool::~ShellTool()
{
	SafeDelete(view);
	SafeDelete(text);
}

VObject *ShellTool::DoMakeContent()
{
	static const char *argv[2];

	argv[0]= Env::GetValue("SHELL", "/bin/csh");
	view= new ShellTextView(this, Rectangle(Point(1000,cFit)), text, argv[0], argv);
	Scroller *shScroller= new Scroller(view, Point(300, 200), cIdNone, eScrollRight);
	shClipper= shScroller->GetClipper();
	shClipper->SetFlag(eVObjLayoutCntl);
	SetFirstHandler(view);
	return shScroller;
}

Point ShellTool::GetInitialWindowSize()
{
	return Point(650, 440);
}

void ShellTool::Control(int id, int detail, void *data)
{
	if (detail == cPartExtentChanged && data == (void*) shClipper)
		view->ChangedViewRect(shClipper->ContentRect());
	else
		Manager::Control(id, detail, data);
}

MenuBar *ShellTool::DoMakeMenuBar()
{
	MenuBar *mb= new MenuBar;

	mb->AddMenu(MakeMenu(cMANAGERMENU));
	mb->AddMenu(MakeMenu(cEDITMENU));
	Menu *m= ShellTextView::MakeMenu(cSHELLMENU);
	m->AppendItem("Show Error@E", cSHOWERR);
	mb->AddMenu(m);
	mb->AddMenuRight(MakeMenu(cHELPMENU));
	return mb;
}

void ShellTool::DoSetupMenu(Menu *m)
{
	Manager::DoSetupMenu(m);
	m->EnableItem(cSHOWERR);
}

void ShellTool::ExtCommand(int from, char *req, char *args, int s, char*& ret, int& l)
{
	// "cmd" command to be submitted
	if (strcmp(req, "cmd") == 0)
		ShellExecute(args);
	else
		Manager::ExtCommand(from, req, args, s, ret, l);
}

void ShellTool::ShellExecute(const char *cmd)
{
	if (view) {
		view->Submit(cmd);
		view->SetSelection(text->Size(), text->Size());
	}
}

